import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入
import Layout from '@/views/Layout'
import Login from '@/views/Login'
import NotFound from '@/views/NotFound'
// 导入搜索
import Search from '@/views/Search'
import SearchResult from '@/views/Search/results'
// 导入文章详情
import Detail from '@/views/article'
// 导入个人中心编辑资料
import UserEdit from '@/views/Layout/User/edit'
import UserChat from '@/views/Layout/User/chat'

// 导入二级路由
import Home from '@/views/Layout/Home'
import Qa from '@/views/Layout/Qa'
import User from '@/views/Layout/User'
import Video from '@/views/Layout/Video'

// 导入token
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home', // 重定向到Home页面，等于redire："Home"
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: 'qa',
        component: Qa
      },
      {
        path: 'user',
        component: User
      },
      {
        path: 'video',
        component: Video
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/user/chat',
    component: UserChat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const token = store.state.user.token.token
const loginURL = ['/user', '/user/edit']
// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断有无token，有token直接放行
  // 没有token再判断去哪个页面，
  // 去user页面拦截到登录，去其他页面放行
  if (token) {
    next() // 有token直接放行
  } else {
    // 没有token再判断要去的页面
    if (loginURL.some(item => to.path === item)) {
      // next('/login')
      router.push({
        path: '/login?',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})
export default router
